package com.slz3.business.frame.steward;

import com.slz3.business.frame.enums.ValidFlag;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.util.MultiValueMap;

import javax.persistence.criteria.*;
import java.util.*;

import static com.slz3.business.frame.util.VE.isNotEmpty;

public class FindJoinSteward {
    public static Collection<? extends Predicate> appoint(
            Root<?> root, CriteriaBuilder cb,
            Class<?> domainClass, MultiValueMap<String, String> params) {
        final List<Predicate> predicateList = new ArrayList<>();
        // 逻辑删除
        predicateList.add(cb.equal(root.get("validFlag").as(ValidFlag.class), ValidFlag.VALID));
        Arrays.stream(ReflectUtils.getBeanProperties(domainClass)).forEach(propertyDescriptor -> {
            String fieldName = propertyDescriptor.getName();
            String paramValue = params.getFirst(fieldName);
            if (isNotEmpty(paramValue)) {
                String typeName = propertyDescriptor.getPropertyType().getTypeName();
                if (typeName.equals(String.class.getTypeName())) {
                    Path<String> exp = root.get(fieldName);
                    Expression<Integer> e = cb.locate(exp, paramValue);
                    Predicate p = cb.gt(e, 0);
                    predicateList.add(p);
                }
            }
        });
        return predicateList;
    }
}
